package co.yixiang.modules.system.util;

import co.yixiang.modules.system.domain.Refund;
import co.yixiang.modules.system.util.xm.XmlUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class RefundUtils {

    /**
     * 微信退款
     *
     * @param rdfund
     * @param req
     * @param type   1-公众号  2-小程序  3-app
     * @return
     * @throws Exception
     */
    public static Map<String, Object> refundUtil(Refund rdfund
            , HttpServletRequest req, Integer type) throws Exception {

        Map<String, Object> mp = new HashMap<String, Object>();
        //设置支付账户信息
        String MchKey = ""; //商户号秘钥
        String MchId = ""; //商户号id
        rdfund.setAppid(BasicInfo.appID);
        rdfund.setMch_id(BasicInfo.MchId);
        MchKey = BasicInfo.MchKey;
        MchId = BasicInfo.MchId;

        rdfund.setNonce_str(PayUtil.getRandomStr());
        rdfund.setSign_type("MD5");
        rdfund.setSign(SignUtil.sign(SignUtil.createRefundSign(rdfund), MchKey));

        try {
            XmlUtil xmlUtil = new XmlUtil();
            xmlUtil.xstream().alias("xml", rdfund.getClass());

            String xml = xmlUtil.xstream().toXML(rdfund);
            String response = PayUtil.ssl(BasicInfo.refundurl, xml, req, MchId);
            System.out.println(response);
            Map<String, String> map = xmlUtil.parseXml(response);
            if ("SUCCESS".equals(map.get("result_code"))) {
                mp.put("stu", true);
                return mp;
            } else {
                mp.put("stu", false);
                mp.put("errMsg", map.get("return_msg"));
                mp.put("errDes", map.get("err_code_des"));
                log.error("微信退款失败》》" + "错误码:" + map.get("return_msg") + "  ;"
                        + "描述:" + map.get("err_code_des"));
                return mp;
            }
        } catch (Exception e) {
            log.error("微信退款异常》》" + e);
            throw new RuntimeException();
        }
    }
}
